import { request } from "../../request/index.js"
Page({

    /**
     * 页面的初始数据
     */
    data: {
        address: {},
        cart: [],
        allChecked: false,
        totalPrice: 0,
        totalNum: 0
    },
    onShow() {
        const address = wx.getStorageSync('address')
        const cart = wx.getStorageSync('cart') || []
        this.setData({
            address
        })
        this.setCart(cart)
    },
    chooseAddress(e) {
        wx: wx.chooseAddress({
            success: (result) => {
                const address = result
                address.all = address.provinceName + address.cityName + address.countyName + address.detailInfo
                wx.setStorageSync('address', address)
            },
        })
    },
    handleChange(e) {
        let { index } = e.currentTarget.dataset
        let cart = this.data.cart
        cart[index].checked = !cart[index].checked
        this.setCart(cart)

    },
    // 购物车的全选按钮，以及总价格，总数量
    setCart(cart) {
        let allChecked = true;
        let totalPrice = 0
        let totalNum = 0
        cart.forEach(item => {
            if (item.checked) {
                totalPrice += item.num * item.goods_price
                totalNum += item.num
            } else {
                allChecked = false
            }
        })
        allChecked = cart.length === 0 ? false : allChecked
        this.setData({
            cart,
            allChecked,
            totalPrice,
            totalNum
        })
        wx.setStorageSync('cart', cart)
    },
    handleAllChecked() {
        let { cart, allChecked } = this.data
        allChecked = !allChecked
        cart.forEach(item => {
            item.checked = allChecked
        })
        this.setCart(cart)
    },
    handleItemNumEdit(e) {
        let { operation, index } = e.currentTarget.dataset
        let { cart } = this.data
        cart[index].num = cart[index].num + operation
        this.setCart(cart)
    }

})